package com.example.leetcode;

/**
 * @Date 2023/2/26
 * @Author Jonathan
 */
public class Code02 {

    public static void main(String[] args) {

    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, p = null;
        // 进位
        int carry = 0;
        int currentVal = 0;
        while (l1 != null && l2 != null) {
            int sum = l1.val + l2.val + carry;
            carry = sum / 10;
            currentVal = sum % 10;
            // 当前值是currentVal 下一个是null
            if (p == null) {
                p = new ListNode(currentVal, null);
            } else {
                p.next = new ListNode(currentVal);
                p = p.next;
            }

            if (head == null) {
                head = p;
            }

            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null) {
            int sum = l1.val + carry;
            carry = sum / 10;
            currentVal = sum % 10;
            // 当前值是currentVal 下一个是null
            if (p == null) {
                p = new ListNode(currentVal, null);
            } else {
                p.next = new ListNode(currentVal, null);
                p = p.next;
            }
            l1 = l1.next;
        }

        while (l2 != null) {
            int sum = l2.val + carry;
            carry = sum / 10;
            currentVal = sum % 10;
            // 当前值是currentVal 下一个是null
            if (p == null) {
                p = new ListNode(currentVal, null);
            } else {
                p.next = new ListNode(currentVal, null);
                p = p.next;
            }
            l2 = l2.next;
        }

        // todo 注意最后的进位
        if (carry > 0) {
            p.next = new ListNode(carry);
        }

        return head;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
